package com.yncmcc.Service;

import com.yncmcc.Entity.DepartmentEntity;
import com.yncmcc.Entity.UserEntity;
import com.yncmcc.Repository.Interface.ContractsRepository;
import com.yncmcc.Repository.Interface.DepartmentRepository;
import com.yncmcc.Repository.Interface.UserRepository;
import com.yncmcc.Service.Interface.UserService;
import com.yncmcc.Util.MD5Util;
import com.yncmcc.Util.STATUS;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.transaction.Transactional;
import java.io.*;
import java.util.*;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * Created by CMCC-sunmo on 2016/9/18.
 */
@Service("userService")
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private ContractsRepository contractsRepository;
    @Autowired
    private DepartmentRepository departmentRepository;
    private Map<String, Object> response;
    @Override
    public UserEntity findByUserId(String userId) {
        UserEntity userEntity = userRepository.findByUserId(userId);
        return userEntity;
    }

    @Override

    public UserEntity findByUserName(String userName) {
        return userRepository.findByUserName(userName);
    }

    @Override
    public List<DepartmentEntity> findDepartmentOfAll() {
        return departmentRepository.findDepartmentAll();
    }
    @Override
    public List<UserEntity> findUser(UserEntity userEntity) {

        List<UserEntity> userEntities = userRepository.findUser(userEntity);
        return userEntities;
    }


    @Override
    public String deleteUser(String userId) {
        String message = "ok";
        UserEntity userEntity = userRepository.findByUserId(userId);
        userEntity.setUserStatus((short) 0);
        userEntity.setUserDTime(new Timestamp(System.currentTimeMillis()));
        userRepository.saveAndFlush(userEntity);
        return message;
    }

    @Override
    public String updateUser(UserEntity userEntity) {
        String message = "ok";
        userEntity.setUserUTime(new Timestamp(System.currentTimeMillis()));
        UserEntity user = userRepository.findByUserId(userEntity.getUserId());
//        System.out.println(user.getUserId());
        user.setUserName(userEntity.getUserName() != null ? userEntity.getUserName() : user.getUserName());
        user.setDeptId((userEntity.getDeptId() != null) ? userEntity.getDeptId() : user.getDeptId());
        user.setUserOaEmail((userEntity.getUserOaEmail() != null) ? userEntity.getUserOaEmail() : user.getUserOaEmail());
        user.setUserOrdinaryEmail((userEntity.getUserOrdinaryEmail() != null) ? userEntity.getUserOrdinaryEmail() : user.getUserOrdinaryEmail());
        user.setUserFullName((userEntity.getUserFullName() != null) ? userEntity.getUserFullName() : user.getUserFullName());
        user.setUserPhone((userEntity.getUserPhone() != null) ? userEntity.getUserPhone() : user.getUserPhone());
        user.setUserRight((userEntity.getUserRight() != null) ? userEntity.getUserRight() : user.getUserRight());
        user.setUserPrimarySalt((userEntity.getUserPrimarySalt() != null) ? userEntity.getUserPrimarySalt() : user.getUserPrimarySalt());
        user.setUserStatus((userEntity.getUserStatus() != null) ? userEntity.getUserStatus() : user.getUserStatus());
        user.setUserCTime((userEntity.getUserCTime() != null) ? userEntity.getUserCTime() : user.getUserCTime());
        user.setUserUTime(new Timestamp(System.currentTimeMillis()));
        user.setUserDTime((userEntity.getUserDTime() != null) ? userEntity.getUserDTime() : user.getUserDTime());
        if(!StringUtils.isBlank(userEntity.getUserPass())){
            String pass = userEntity.getUserPass();
            user.setUserPass(pass);
        }
        userRepository.saveAndFlush(user);
        return message;
    }

    @Override
    public String addUser(UserEntity userEntity) {
        String message = "ok";
        UserEntity check = userRepository.findByUserName(userEntity.getUserName());
        if(StringUtils.isBlank(userEntity.getUserName())){
            message = "用户名为空";
            return message;
        }else if(check != null){
            message = "用户已存在";
            return message;
        }else if(StringUtils.isBlank(userEntity.getUserPass())){
            message = "用户密码为空";
            return message;
        }else if(StringUtils.isBlank(userEntity.getDeptId())){
            message = "用户部门为空";
            return message;
        }else if(StringUtils.isBlank(userEntity.getUserOaEmail())){
            message = "用户OA邮箱为空";
            return message;
        }else if(StringUtils.isBlank(userEntity.getUserOrdinaryEmail())){
            message = "用户名普通邮箱为空";
            return message;
        }else if(StringUtils.isBlank(userEntity.getUserFullName())){
            message = "用户姓名为空";
            return message;
        }else if(StringUtils.isBlank(userEntity.getUserPhone())){
            message = "用户电话为空";
            return message;
        }else if(userEntity.getUserRight() == null) {
            message = "用户权限不为空";
            return message;
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        int random = (int)(Math.random()*10000);
        userEntity.setUserId(sdf.format(new Date()) + random);
        userEntity.setUserCTime(new Timestamp(System.currentTimeMillis()));
        String pass = MD5Util.calc(userEntity.getUserPass() + random);
        userEntity.setUserPass(pass);
        userEntity.setUserPrimarySalt(random  + "");
        userEntity.setUserStatus((short) 1);
        userRepository.save(userEntity);
        return message;
    }

    @Override
    public boolean checkPass(String userId, String password) {
        boolean flag = false;
        UserEntity check = userRepository.findByUserId(userId);
        String pass = MD5Util.calc(password + check.getUserPrimarySalt());
//        String pass = password;
        if(pass.equals(check.getUserPass())){
            flag = true;
        }
        return flag;
    }

    @Override
    public String addUserByExcel(MultipartFile file) throws IOException, BiffException {
        String message = "";

        File file1 = new File("temp");
        FileOutputStream fileOutputStream = new FileOutputStream(file1);
        BufferedOutputStream outputStream = new BufferedOutputStream(fileOutputStream);
        outputStream.write(file.getBytes());
        Workbook workbook = Workbook.getWorkbook(file1);
        Sheet sheet = workbook.getSheet(0);
        int row = sheet.getRows();

        /* excel列顺序 */
        /* 用户名称 */
        /* 用户密码 */
        /* 用户部门ID */
        /* 用户OA邮箱 */
        /* 用户普通邮箱 */
        /* 用户姓名 */
        /* 用户手机 */

        for (int i = 1; i < row; i++) {
            Cell cell = null;
            UserEntity userEntity = new UserEntity();

            /* 用户ID */
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            int random = (int)(Math.random()*10000);
            userEntity.setUserId(sdf.format(new Date()) + random);

            /* 用户名称 */
            if (null != (cell = sheet.getCell(0, i)) && !StringUtils.isBlank(cell.getContents())) {
                String str = cell.getContents();
                userEntity.setUserName(str);
            } else {
                message = "第" + (i+1) + "行：用户名称不为空";
                return message;
            }

            /* 用户密码 */
            if (null != (cell = sheet.getCell(1, i)) && !StringUtils.isBlank(cell.getContents())) {
                String str = cell.getContents();
                String pass = MD5Util.calc(MD5Util.calc(str) + random);
//                String pass = MD5Util.calc(str);
                userEntity.setUserPass(pass);
            }else {
                message = "第" + (i+1) + "行：用户密码不为空";
                return message;
            }


            /* 用户部门ID */
            if (null != (cell = sheet.getCell(2, i)) && !StringUtils.isBlank(cell.getContents())) {
                String str = cell.getContents();
                userEntity.setDeptId(str);
            }else {
                message = "第" + (i+1) + "行：用户部门ID不为空";
                return message;
            }

            /* 用户OA邮箱 */
            if (null != (cell = sheet.getCell(3, i)) && !StringUtils.isBlank(cell.getContents())) {
                String str = cell.getContents();
                userEntity.setUserOaEmail(str);
            }else {
                message = "第" + (i+1) + "行：用户OA邮箱不为空";
                return message;
            }

            /* 用户普通邮箱 */
            if (null != (cell = sheet.getCell(4, i)) && !StringUtils.isBlank(cell.getContents())) {
                String str = cell.getContents();
                userEntity.setUserOrdinaryEmail(str);
            }else {
                message = "第" + (i+1) + "行：用户普通邮箱不为空";
                return message;
            }

            /* 用户姓名 */
            if (null != (cell = sheet.getCell(5, i)) && !StringUtils.isBlank(cell.getContents())) {
                String str = cell.getContents();
                userEntity.setUserFullName(str);
            }else {
                message = "第" + (i+1) + "行：用户姓名不为空";
                return message;
            }

            /* 用户手机 */
            if (null != (cell = sheet.getCell(6, i)) && !StringUtils.isBlank(cell.getContents())) {
                String str = cell.getContents();
                userEntity.setUserPhone(str);
            }else {
                message = "第" + (i+1) + "行：用户姓名不为空";
                return message;
            }

            /* 用户权限 */
            userEntity.setUserRight(Short.parseShort("3"));

            /* 用户加密盐值 */
            userEntity.setUserPrimarySalt(random + "");

            /* 用户状态 */
            userEntity.setUserStatus(Short.parseShort("1"));

            /* 用户创建时间 */
            userEntity.setUserCTime(new Timestamp(System.currentTimeMillis()));

            if (checkUser(userEntity))
                userRepository.saveAndFlush(userEntity);
        }
        return null;
    }

    @Override
    public boolean checkUser(UserEntity userEntity) {
        UserEntity check = null;
        if (!StringUtils.isBlank(userEntity.getUserName())) {
            check = userRepository.findByUserName(userEntity.getUserName());
        }
        if (check == null) {
            return true;
        } else
            return false;
    }
}